declare @month nvarchar(100)=(select [MAX_MONTH] from [DATE_EM_REPORT])
declare @date_end_month nvarchar(100)= (select [MAX_DATE_ENDMONTH] from [DATE_EM_REPORT])

exec('
IF EXISTS
(SELECT *
FROM DBO.SYSOBJECTS O
WHERE O.XTYPE IN (''U'') AND O.NAME = ''TOI_'+@month+''')
DROP TABLE TOI_'+@month+'

SELECT CIF,DAO_CIF,SUM(AMT) AS TOI INTO TOI_'+@month+'
FROM TRANGDTT18.SME2017.DBO.NFI_TOI_'+@month+'
WHERE TYPE=''TOI''
GROUP BY DAO_CIF,CIF

delete from TBL_TOI

insert TBL_TOI
SELECT BUSINESS_DATE='''+@date_end_month+''',A.*,B.DAO,B.CUS_NAME,b.INDUSTRY_NAME,b.INDUSTRY_NAME_EN, b.branch_id, b.dao_name --INTO TBL_TOI
FROM TOI_'+@month+' A
LEFT JOIN TBL_CUSTOMER B
ON A.CIF=b.CIF COLLATE DATABASE_DEFAULT
')

delete from tbl_toi where DAO is null

update b
set b.date_data = a.CreatedTime
from (select max(BUSINESS_DATE) as CreatedTime from TBL_TOI) a,  TBL_DATE_BUSINESS b
where b.name_table = 'TBL_TOI'